// pages/chinese/strokes/strokes.js
// 笔画数据
const strokeData = {
  "basic": [
    { text: "一", name: "横", desc: "从左到右" },
    { text: "丨", name: "竖", desc: "从上到下" },
    { text: "丿", name: "撇", desc: "从右上到左下" },
    { text: "丶", name: "点", desc: "从上到下" },
    { text: "乛", name: "捺", desc: "从左上到右下" },
    { text: "乚", name: "弯钩", desc: "弯曲的钩" },
    { text: "亅", name: "竖钩", desc: "竖加钩" },
    { text: "乀", name: "提", desc: "从下到上" }
  ],
  "compound": [
    { text: "十", name: "横竖", desc: "横+竖" },
    { text: "人", name: "撇捺", desc: "撇+捺" },
    { text: "口", name: "口字框", desc: "四边围合" },
    { text: "日", name: "日字框", desc: "四边围合" },
    { text: "田", name: "田字框", desc: "四边围合" },
    { text: "木", name: "木字旁", desc: "横竖撇捺" },
    { text: "水", name: "水字旁", desc: "三点水" },
    { text: "火", name: "火字旁", desc: "四点底" }
  ]
};

Page({
  data: {
    categoryList: [
      { key: 'basic', name: '基本笔画' },
      { key: 'compound', name: '复合笔画' }
    ],
    currentCategory: '',
    currentStrokes: [],
    selectedStroke: null,
    canvasContext: null,
    canvasNode: null,
    canvasWidth: 0,
    canvasHeight: 0,
    canvasLeft: 0,
    canvasTop: 0,
    isDrawing: false,
    lastX: 0,
    lastY: 0
  },

  onLoad() {
    // 默认选择基本笔画
    this.selectCategory({ currentTarget: { dataset: { category: 'basic' } } });
  },

  onReady() {
    // Canvas 初始化延迟到选择笔画后
  },

  initCanvas() {
    // 初始化 canvas（在选择笔画后调用）
    const query = this.createSelectorQuery();
    query.select('#strokeCanvas')
      .fields({ node: true, size: true })
      .boundingClientRect()
      .exec((res) => {
        if (res && res[0] && res[0].node) {
          const canvas = res[0].node;
          const ctx = canvas.getContext('2d');
          const dpr = wx.getSystemInfoSync().pixelRatio;
          const width = res[0].width;
          const height = res[0].height;
          
          canvas.width = width * dpr;
          canvas.height = height * dpr;
          ctx.scale(dpr, dpr);
          
          // 设置默认样式
          ctx.strokeStyle = '#333';
          ctx.lineWidth = 4;
          ctx.lineCap = 'round';
          ctx.lineJoin = 'round';
          
          this.canvasContext = ctx;
          this.canvasNode = canvas;
          this.setData({
            canvasWidth: width,
            canvasHeight: height,
            canvasLeft: res[0].left || 0,
            canvasTop: res[0].top || 0
          });
        } else {
          // 如果获取失败，延迟重试
          setTimeout(() => {
            this.initCanvas();
          }, 100);
        }
      });
  },

  selectCategory(e) {
    const category = e.currentTarget.dataset.category;
    const strokes = strokeData[category] || [];
    
    this.setData({
      currentCategory: category,
      currentStrokes: strokes,
      selectedStroke: null
    });
    
    // 清除画布（如果已初始化）
    if (this.canvasContext) {
      this.clearCanvas();
    }
  },

  selectStroke(e) {
    const index = e.currentTarget.dataset.index;
    const stroke = this.data.currentStrokes[index];
    
    this.setData({
      selectedStroke: stroke
    });
    
    // 延迟初始化 canvas（等待 DOM 渲染）
    setTimeout(() => {
      this.initCanvas();
    }, 100);
  },

  clearCanvas() {
    if (this.canvasContext && this.data.canvasWidth && this.data.canvasHeight) {
      this.canvasContext.clearRect(0, 0, this.data.canvasWidth, this.data.canvasHeight);
    }
    this.setData({
      isDrawing: false,
      lastX: 0,
      lastY: 0
    });
  },

  showDemo() {
    // 显示示范动画（简化版，实际可以添加动画效果）
    wx.showToast({
      title: '请参考上方笔画',
      icon: 'none',
      duration: 2000
    });
  },

  onTouchStart(e) {
    if (!this.canvasContext) {
      // 如果 canvas 未初始化，尝试初始化
      this.initCanvas();
      return;
    }
    
    const touch = e.touches[0];
    // 计算相对于 canvas 的坐标
    const x = touch.clientX - this.data.canvasLeft;
    const y = touch.clientY - this.data.canvasTop;
    
    this.setData({
      isDrawing: true,
      lastX: x,
      lastY: y
    });
    
    this.canvasContext.beginPath();
    this.canvasContext.moveTo(x, y);
  },

  onTouchMove(e) {
    if (!this.data.isDrawing || !this.canvasContext) return;
    
    const touch = e.touches[0];
    // 计算相对于 canvas 的坐标
    const x = touch.clientX - this.data.canvasLeft;
    const y = touch.clientY - this.data.canvasTop;
    
    this.canvasContext.lineTo(x, y);
    this.canvasContext.stroke();
    
    this.setData({
      lastX: x,
      lastY: y
    });
  },

  onTouchEnd() {
    this.setData({
      isDrawing: false
    });
  }
});

